package com.shop.auth;

import com.shop.entity.SysUser;
import com.shop.entity.dto.RolePerssionDTO;
import com.shop.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class RolePerssionRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 角色和权限授权
     * @param principalCollection
     * @return AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String name = (String) principalCollection.getPrimaryPrincipal();
        List<RolePerssionDTO> rolePerssionDTO = sysUserService.findRolePerssionByUserName(name);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        rolePerssionDTO.forEach((rolePerssionData)->{
            simpleAuthorizationInfo.addRole( rolePerssionData.getUserRole());
            simpleAuthorizationInfo.addStringPermission(rolePerssionData.getUserPerssion());
        });
        return simpleAuthorizationInfo;

    }

    /**
     * 登录认证
     * @param authenticationToken
     * @return AuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (authenticationToken.getPrincipal().toString().isEmpty()) {
            return null;
        }
        String name = authenticationToken.getPrincipal().toString();
        SysUser sysUser = sysUserService.findSysUserByUserName(name);
        if (sysUser == null) {
            return null;
        } else {
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, sysUser.getUserPassword(), ByteSource.Util.bytes(sysUser.getSalt()), getName());
            return simpleAuthenticationInfo;
        }
    }
}
